import { Request, Response } from 'express';
import { query } from 'common/src/config/database';

interface Word {
  id: number;
  category_id: number;
  word: string;
  translation: string;
  example: string;
  created_at: Date;
  updated_at: Date;
}

interface WordLearningRecord {
  id: number;
  user_id: number;
  word_id: number;
  status: string;
  accuracy: number;
  review_count: number;
  last_review_at: Date;
  created_at: Date;
  updated_at: Date;
}

// 获取单词列表
export const getWordList = async (req: Request, res: Response) => {
  try {
    const { category, page = 1, limit = 20 } = req.query;
    const offset = (Number(page) - 1) * Number(limit);

    let sql = 'SELECT * FROM words';
    let countSql = 'SELECT COUNT(*) as total FROM words';
    const params: any[] = [];

    if (category) {
      sql += ' WHERE category_id = ?';
      countSql += ' WHERE category_id = ?';
      params.push(category);
    }

    sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(Number(limit), offset);

    const [words] = await query<Word>(sql, params);
    const [countResult] = await query<{ total: number }>(countSql, category ? [category] : []);
    const total = countResult[0].total;

    res.json({
      success: true,
      data: {
        words,
        pagination: {
          total,
          page: Number(page),
          limit: Number(limit)
        }
      }
    });
  } catch (error) {
    console.error('获取单词列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取单词列表失败'
    });
  }
};

// 获取单词详情
export const getWordDetail = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const [words] = await query<Word>(
      'SELECT * FROM words WHERE id = ?',
      [id]
    );
    const word = words[0];

    if (!word) {
      return res.status(404).json({
        success: false,
        message: '单词不存在'
      });
    }

    res.json({
      success: true,
      data: word
    });
  } catch (error) {
    console.error('获取单词详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取单词详情失败'
    });
  }
};

// 记录学习
export const recordLearning = async (req: Request, res: Response) => {
  try {
    const { wordId, status, accuracy } = req.body;
    const userId = req.user.userId;

    const [_, result] = await query(
      `INSERT INTO word_learning_records 
       (user_id, word_id, status, accuracy, review_count, last_review_at)
       VALUES (?, ?, ?, ?, 0, NOW())`,
      [userId, wordId, status, accuracy]
    );

    const [records] = await query<WordLearningRecord>(
      'SELECT * FROM word_learning_records WHERE id = ?',
      [result.insertId]
    );

    res.json({
      success: true,
      data: records[0]
    });
  } catch (error) {
    console.error('记录学习错误:', error);
    res.status(500).json({
      success: false,
      message: '记录学习失败'
    });
  }
};

// 获取复习计划
export const getReviewPlan = async (req: Request, res: Response) => {
  try {
    const userId = req.user.userId;
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const [records] = await query<WordLearningRecord>(
      `SELECT r.*, w.* 
       FROM word_learning_records r
       JOIN words w ON r.word_id = w.id
       WHERE r.user_id = ? AND r.last_review_at < ?
       ORDER BY r.last_review_at ASC
       LIMIT 20`,
      [userId, today]
    );

    res.json({
      success: true,
      data: records
    });
  } catch (error) {
    console.error('获取复习计划错误:', error);
    res.status(500).json({
      success: false,
      message: '获取复习计划失败'
    });
  }
}; 